package com.easy_helth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easy_helth.common.R;
import com.easy_helth.entity.User;
import com.easy_helth.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;


    /**
     * 新增用户
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody User User){
        log.info("新增管理员{}" , User.toString());
        userService.save(User);
        return R.success("添加成功");
    }

    /**
     * 用户分页查询
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        Page pageInfo = new Page(page,pageSize);
//        构造条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),User::getUserName,name);
//        添加排序条件
        queryWrapper.orderByDesc(User::getUpdate_time);
//        执行查询
        userService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改用户
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody User User){
        log.info(User.toString());
        Long empId = (Long) request.getSession().getAttribute("User");
        User.setUpdate_time(LocalDateTime.now());
        userService.updateById(User);
        return R.success("员工修改成功");
    }

    //    查询用户
//    PathVariable指从路径得到参数
    @GetMapping("/{id}")
    public R<User> getById(@PathVariable int id){
        log.info("根据id查询");
        User User = userService.getById(id);
        return R.success(User);
    }

    /**
     * 获取用户分布总数
     * @return
     */
    @GetMapping("/getUserNumber")
    public R<Map<String,Integer>> getUserNumber(){
        Map<String,Integer> addCount = userService.getUserNumber();
        return R.success(addCount);
    }

    /**
     * 获取用户年龄分布
     * @return
     */
    @GetMapping("getUserAge")
    public R<Map<String,Integer>> getUserAge(){
        Map<String,Integer> userAge = userService.getUserAge();
        log.info(String.valueOf(userAge));
        return R.success(userAge);
    }
}

